import { updateQueue } from "./Component";

/**
 * 实现事件委托，把所有的事件都绑定到document上
 * @param {*} dom
 * @param {*} eventType
 * @param {*} handler
 */
export function addEvent(dom, eventType, handler) {
  let store;
  if (dom.store) {
    store = dom.store;
  } else {
    dom.store = {};
    store = dom.store;
  }
  store[eventType] = handler;
  if (!document[eventType]) {
    // 如果有很多个元素都绑定click事件，往document只挂一次
    document[eventType] = dispatchEvent;
  }
}
function dispatchEvent(event) {
  let { target, type } = event;
  let eventType = `on${type}`; // onclick
  updateQueue.isBatchingUpdate = true; // 切换为批量更新模式
  let syntheticEvent = createSyntheticEvent(event);
  //模拟事件冒泡的过程
  while (target) {
    let { store } = target;
    let handler = store && store[eventType];
    handler && handler.call(target, syntheticEvent);
    target = target.parentNode;
  }

  updateQueue.isBatchingUpdate = false;
  updateQueue.batchUpdate();
}

function createSyntheticEvent(event) {
  let syntheticEvent = {};
  for (let key in event) {
    syntheticEvent[key] = event[key];
  }
  return syntheticEvent;
}
